package com.netease.nim.demo.common.media.audioplayer;

import java.io.IOException;

import android.content.Context;
import android.media.MediaRecorder;
import android.util.Log;

import com.netease.nim.demo.util.storage.StorageType;
import com.netease.nim.demo.util.storage.StorageUtil;

public class SysAudioRecordControl {

	private static final String TAG = "SysAudioRecordControl";

	private Context context;

	private MediaRecorder mRecorder = null;

	private static SysAudioRecordControl instance = null;

	public static SysAudioRecordControl getInstance(Context context) {
		if (instance == null) {
			synchronized (SysAudioRecordControl.class) {
				if (instance == null) {
					instance = new SysAudioRecordControl(context.getApplicationContext());
				}
			}
		}

		return instance;
	}

	public SysAudioRecordControl(Context context) {
		this.context = context;
	}

	public void startRecord(String name) {
		if (mRecorder != null) {
			endRecord();
		}

		final String filePath = StorageUtil.getWritePath(name, StorageType.TYPE_AUDIO);

		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
		mRecorder.setOutputFile(filePath);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
		try {
			mRecorder.prepare();
		} catch (IOException e) {
			Log.e(TAG, "prepare() failed");
		}

		mRecorder.start();
	}

	public void endRecord() {
		if (mRecorder != null) {
			mRecorder.stop();
			mRecorder.release();
			mRecorder = null;
		}
	}
}
